#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTimer>
#include "udpsender.h"
#include "protocol.h"

#include <QJsonDocument>
#include <QJsonObject>
#include <QFile>
#include <QTextStream>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_sendCar1_clicked();
    void on_sendCar2_clicked();
    void on_sendDrone_clicked();
    
    // 新增按钮的槽函数
    void on_btnResetConnection_clicked();
    void on_btnToggleNoise_clicked();
    void on_btnSetFrequency_clicked();

    // 定时器触发后，实际发送数据的槽函数
    void sendCar1Data();
    void sendCar2Data();
    void sendDroneData();
    
    // 噪声生成辅助函数
    int addNoise(int originalValue, int noiseRange);
private:
    Ui::MainWindow *ui;
    UdpSender* m_sender;

    // 为每种数据类型声明一个定时器
    QTimer *m_timerCar1;
    QTimer *m_timerCar2;
    QTimer *m_timerDrone;
    
    // 噪声状态标志
    bool m_noiseEnabled;
    
    // JSON数据存储结构 - 每个字段都有对应的存在性标记
    struct JsonCarData {
        int longitude = 0;
        int latitude = 0;
        int heading = 0;
        int label1 = 0, deviation1 = 0;
        int label2 = 0, deviation2 = 0;
        int label3 = 0, deviation3 = 0;
        bool isValid = false;  // 标记数据是否有效
        
        // 字段存在性标记
        bool hasLongitude = false;
        bool hasLatitude = false;
        bool hasHeading = false;
        bool hasLabel1 = false, hasDeviation1 = false;
        bool hasLabel2 = false, hasDeviation2 = false;
        bool hasLabel3 = false, hasDeviation3 = false;
    };
    
    struct JsonDroneData {
        int longitude = 0;
        int latitude = 0;
        int altitude = 0;
        int heading = 0;
        int roll = 0;
        int pitch = 0;
        int label1 = 0, target1X = 0, target1Y = 0;
        int label2 = 0, target2X = 0, target2Y = 0;
        int label3 = 0, target3X = 0, target3Y = 0;
        bool isValid = false;  // 标记数据是否有效
        
        // 字段存在性标记
        bool hasLongitude = false;
        bool hasLatitude = false;
        bool hasAltitude = false;
        bool hasHeading = false;
        bool hasRoll = false;
        bool hasPitch = false;
        bool hasLabel1 = false, hasTarget1X = false, hasTarget1Y = false;
        bool hasLabel2 = false, hasTarget2X = false, hasTarget2Y = false;
        bool hasLabel3 = false, hasTarget3X = false, hasTarget3Y = false;
    };
    
    // JSON数据成员变量
    JsonCarData m_jsonCar1Data;
    JsonCarData m_jsonCar2Data;
    JsonDroneData m_jsonDroneData;
    bool m_useJsonData = false;  // 标记是否使用JSON数据

    CarData readCarData(int carIndex);
    DroneData readDroneData();
    
    // JSON数据加载函数
    void loadDataFromJson();
    
    // 将JSON数据更新到UI控件
    void updateUIFromJsonData();
    
    // 获取当前设置的定时器间隔
    int getCurrentInterval() const;
};
#endif // MAINWINDOW_H
